<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\Userdetail;
use App\Address;
use Auth;
use App\Orders;
use Hash;
use DB;



class PersonController extends Controller
{
    /**
    * 前台用户中心首页
    */
    public function index(Request $request) {
        //检查是否登陆
        if(Auth::check()){
            $id = Auth::user()->id;   
            //获取用户对象
            $user = User::find($id);
            //获取用户详情
            $userinfo = $user->userdetail;
            //获取用户等级
            $lev = self::getLevel($userinfo['score']);
            //获取用户的优惠券数
            $coupons = $user->coupons()->select(DB::raw('count(*) as count'))->first();
            //获取用户的订单
            $orders = $user->orders()->select(DB::raw('count(*) as order_count, oStatus'))->groupBy('oStatus')->orderBy('oStatus')->get();
            // 获取用户的收藏
            $colls = $user->collect()->offset(0)->limit(5)->get();
        	return view('home.person.index',['user'=>$user,'userinfo'=>$userinfo,'coupons'=>$coupons,'lev'=>$lev,'orders'=>$orders,'colls'=>$colls]);
         }else{
            return redirect('/auth/login');
         }
    }

    /**
     * 接收个人中心主页 收藏商品 “更多” 的ajax
     */

    public function moreAjax(Request $request){
        $uid = $request->uid;
        $num = $request->num;
        $user = User::find($uid);
        $colls = $user->collect()->offset($num)->limit(5)->get();
        echo json_encode($colls);
        
    }
    /**
     * 通过积分获取等级
     */
    public static function getLevel($score)
    {
        if($score<=500){
            return 'lev1';
        }elseif($score>500 && $score<=2000){
            return 'lev2';
        }elseif($score>2000 && $score<=5000){
            return 'lev3';
        }else{
            return 'lev4';
        }
    }
    /**
    * 前台用户个人资料修改页面
    */
    public function info(Request $request) {
        if(Auth::check()){
            $user = Auth::user();
            $id = $user->id;
            $res = DB::table('users')
            -> leftJoin('userdetail','users.id','=','userdetail.id')
            ->where('users.id','=',$id)
            ->first();
            // dd($res);die;
            $lev = self::getLevel($res->score);
        	return view('home.person.info', [
                'res' => $res,
                'lev' => $lev
                ]);
        }else{
            return redirect('/auth/login');
        }
    }

    /**
     * 前台用户个人资料修改操作
     */
    public function updateInfo(Request $request)
    {   
        $data = $request -> except(['_token']);
        //执行数据库插入
        $res = DB::table('userdetail')->where('id','=',$data['id'])->update($data);

        if($res) {
        }else{
            return back();
        }

    }

    /**
    * 前台用户个人安全设置
    */
    public function safe() {

         if(Auth::check()){
            $user = Auth::user();
            $id = $user->id;
            $res = DB::table('users')
            -> leftJoin('userdetail','users.id','=','userdetail.id')
            ->where('users.id','=',$id)
            ->first();
            // dd($res);die;
            $lev = self::getLevel($res->score);
            return view('home.person.safe', [
                'res' => $res,
                'lev' => $lev
                ]);
        }else{
            return redirect('/auth/login');
        }
    }

    /**
     *显示修改密码页面 
     */
    public function password()
    {
        return view('home.person.password');
    }

    /**
     * 执行修改密码
     * 
     */
    public function changePass(Request $request)
    {
        $before = $request->before;
        $password = Auth::user()->password;
        $newPass = Hash::make($request->new);
        $id = Auth::user()->id;
        if(Hash::check($before,$password)){
            $this->validate($request,
            [
                'new'=>'required|same:confirm'
            ],[
                'new.required'=>'请填写新密码',
                'new.same'=>'两次输入密码不一致'
            ]);
            DB::table('users')->where('id','=',$id)->update(['password'=>$newPass]);
            Auth::logout();
            return redirect('/auth/login');
        }else{
            //withInput() 是把表单提交的参数写到缓存  页面用{{old('username')}} 提取
            return back()->with('error','<script>alert("密码错误")</script>');
        }
        
    }

    /**
     * 显示换绑邮箱页面
     */
    public function email()
    {
        return view('home.person.email');
    }

    /**
     * 执行修改邮箱
     */
    public function changeEmail(Request $request)
    {

        $email = $request->email;
        $id = Auth::user()->id;
            $this->validate($request,
            [
                'email'=>'required|email'
            ],[
                'email.email'=>'填写正确的邮箱'
            ]);
            DB::table('users')->where('id','=',$id)->update(['email'=>$email]);
            return back()->with('info','<script>alert("修改成功")</script>');
    }

    /**
    * 前台用户个人地址管理
    */
    public function address(Request $request) {
        if(Auth::check()){
            $uid = Auth::user()->id;
            $address = DB::table('address')->where('uid','=',$uid)->get();
        	return view('home.person.address',['address'=>$address,'uid'=>$uid]);
        }else{
            return redirect('/auth/login');
        }
    }

    /**
     * 存储新增地址
     * 
     */
    public function addAddress(Request $request){
        $this->validate($request, [
            'uid'=>'required',
            'name' => 'required|max:255',
            'phone' => 'required|regex:/^\d{11}$/',
            'prov'=>'required',
            'city'=>'required',
            'detail'=>'required'
        ],[
            'name.required'=>'收货人必填',
            'phone.required'=>'手机号必填',
            'phone.regex'=>'填写正确的手机号',
            'prov.required'=>'省必填',
            'city.required'=>'城市必填',
            'detail.required'=>'详细地址必填'
        ]);

        $data = $request->except('_token');
        DB::table('address')->insert($data);
        return redirect('/person/address');
    }

    /**
     * 显示编辑修改收货地址页面
     */
    public function edit($id)
    {   
        $address = Address::find($id);
        return view('home.person.edit',['address'=>$address]);
    }

    /**
     * 执行修改收货地址
     */

    public function doEdit(Request $request,$id)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'phone' => 'required|regex:/^\d{11}$/',
            'prov'=>'required',
            'city'=>'required',
            'detail'=>'required'
        ],[
            'name.required'=>'收货人必填',
            'phone.required'=>'手机号必填',
            'phone.regex'=>'填写正确的手机号',
            'prov.required'=>'省必填',
            'city.required'=>'城市必填',
            'detail.required'=>'详细地址必填'
        ]);
        $data = $request->except('_token');
        DB::table('address')->where('id','=',$id)->update($data);
        return redirect('/person/address');
    }
    /**
     *执行默认地址修改 
     */
    public function default($id)
    {
        DB::table('address')->where('id','=',$id)->update(['status'=>0]);
        DB::table('address')->where('id','<>',$id)->update(['status'=>1]);
    }

    /**
     * 执行删除收货地址
     */
    public function delAddress($id)
    {
        $res = DB::table('address')->where('id','=',$id)->delete();
        if($res){
            echo 'success';
        }

    }

    /**
    * 个人订单管理
    */
    public function order() {
        $uid = Auth::user()->id;
        //读取订单信息
        $orders = Orders::where('uid','=',$uid)->get();
        //读取订单中的商品信息
        foreach($orders as $k=>$v){
            $v->goods = DB::table('goods')->where('id','=',$v->goods_id)->first();
        }
        //解析模版,分配变量
    	return view('home.person.order',['orders'=>$orders]);
    }


    /**
    * 个人订单详情
    */
    public function orderinfo($id) {
        $orders = Orders::where('id','=',$id)->first();
        $goods = DB::table('goods')->where('id','=',$orders->goods_id)->first();
        $orders->goods = $goods;
        $address = DB::table('address')->where('id','=',$orders->addr_id)->first(); 
    	return view('home.person.orderinfo',['address'=>$address,'orders'=>$orders]);
    }

    /**
     * 确认收货
     */
    public function shouhuo($id)
    {
        DB::table('orders')->where('id','=',$id)->update(['oStatus'=>3]);
    }

    /**
    * 个人退换货管理
    */
    public function change() {
    	return view('home.person.change');
    }


    /**
    * 个人优惠券
    */
    public function coupon() {
        $uid = Auth::user()->id;
        $user = User::find($uid);
        $coupons = $user->coupons;
    	return view('home.person.coupon',['coupons'=>$coupons]);
    }

    /**
     * 删除优惠券
     */
    public function delCoupon($id)
    {
        DB::table('user_coupons')->where('id','=',$id)->delete();
    }
    /**
    * 个人红包
    */
    public function bonus() {
    	return view('home.person.bonus');
    }


    /**
    * 个人账单明细
    */
    public function bill() {
    	return view('home.person.bill');
    }


    /**
    * 个人收藏
    */
    public function collection() {
        if(Auth::check()){
            $id = Auth::user()->id;
            //获取用户对象
            $user = User::find($id);
            $colls = $user->collect()->offset(0)->limit(5)->get();
    	   return view('home.person.collection',['colls'=>$colls,'user'=>$user]);
        }else{
            return redirect('/auth/login');
        }
    }
    /**
     * 执行取消收藏
     */
    public function cancel(Request $request)
    {
        $uid = Auth::user()->id;
        $gid = $request->id;
        DB::table('goods_user')->where('user_id','=',$uid)->where('goods_id','=',$gid)->delete();
    }

    /**
     * 将收藏商品加入购物车
     */
    
    public function cart($id)
    {
        if(Auth::check()){
            $uid = Auth::user()->id;
            $res = DB::table('cart')->where('users_id','=',$uid)->where('goods_id','=',$id)->first(); 
            if($res){
                $num = $res->num+1;
                DB::table('cart')->where('users_id','=',$uid)->where('goods_id','=',$id)->update(['num'=>$num]);
            }else{       
                $data['users_id'] = $uid;
                $data['goods_id'] = $id;
                DB::table('cart')->insert($data);
           
            }
        }else{
            return redirect('/auth/login');
        }
    }

    /**
    * 个人浏览足迹
    */
    public function foot() {
    	return view('home.person.foot');
    }


	/**
    * 个人评价
    */
    public function comment() {
    	return view('home.person.comment');
    }


	/**
    * 个人消息
    */
    public function news() {
    	return view('home.person.news');
    }



}
